<template>
  <div class="social-media-chart-container" ref="chartContainer">
    <div class="switch-wrapper" @click.stop>
      <div class="social-media-info">
        <div class="platform-details">
          <div class="platform-title">Global Score</div>
          <div class="platform-review-count">9.37</div>
          <div class="platform-review-label">Scores</div>
        </div>
        <!-- <div class="platform-switch">
          <div class="switch-label">Social media</div>

          <el-switch
            v-model="mediaSwitch"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :width="45"
            active-text="on"
            @change="handleSwitchChange"
          >
          </el-switch>
        </div> -->
      </div>
      <div class="chart-container" style="pointer-events: none">
        <PieChart
          :option="optionAnnular"
          :height="chartHeight"
          :width="chartWidth"
        ></PieChart>
      </div>
    </div>
  </div>
</template>

<script>
import { fontChart } from "@/utils/echartPxToRem";

import PieChart from "@components/common/PieChart.vue";

export default {
  components: {
    PieChart,
  },
  data() {
    return {
      chartWidth: "100%", // 初始宽度
      chartHeight: "1.4375rem", // 保持固定高度或动态计算  
      mediaSwitch: true,
      currentChartData: null, // 新增：存储当前激活的图表数据
      chartInstance: null, // 存储图表实例
      // 新增：存储两种状态下的数据
      chartData: {
        socialMedia: [
          {
            value: 500,
            name: "Direct booking",
            itemStyle: { color: "#B2B2B2" },
          },
          {
            value: 364,
            name: "Information Platforms",
            itemStyle: { color: "#2FAA68" },
          },
          { value: 161, name: "OTAs", itemStyle: { color: "#4199E1" } },
        ],
        allSources: [
          { value: 350, name: "Social Media", itemStyle: { color: "#A563EA" } },
          {
            value: 420,
            name: "Direct booking",
            itemStyle: { color: "#B2B2B2" },
          },
          {
            value: 280,
            name: "Information Platforms",
            itemStyle: { color: "#2FAA68" },
          },
          { value: 250, name: "OTAs", itemStyle: { color: "#4199E1" } },
        ],
      },
      optionAnnular: {
        tooltip: {
          trigger: "item",
        },
        legend: {
          // 图例  标注各种颜色代表的模块
          orient: "vertical",
          left: "0%",
          bottom: "0%",
          //  left: "90%", // 控制图例的位置
          // symbol: `image://${require("@/assets/Booking.png")}`,
          itemWidth: fontChart(20), // 图例颜色块的宽度和高度
          itemHeight: fontChart(20),
          // icon: `image://${require("@/assets/Booking.png")}`, // 图例前的图标为圆点
          itemGap: fontChart(2),
          borderWidth: 0, // 图例边框线宽
          padding: [10, 0, 0, 24],
          formatter: (name) => {
            const item = this.optionAnnular.series[0].data.find(
              (dataItem) => dataItem.name === name
            );
            if (!item) return name;

            // 计算总数据和
            const total = this.optionAnnular.series[0].data.reduce(
              (sum, item) => sum + item.value,
              0
            );
            if (total === 0) return name;

            // 计算百分比（保留1位小数）
            const percent = ((item.value / total) * 100).toFixed(1);

            // 返回拼接后的文本（名称 + 值 + 百分比）
            return `${name}  {valueStyle|${item.value.toLocaleString()}k}  {percentStyle|(${percent}%)}`;
          },

          // 新增：配置 rich 样式
          textStyle: {
            color: "#454545",
            fontSize: fontChart(12), // name 的字体大小（普通字重）
            rich: {
              valueStyle: {
                fontWeight: "bold", // 数字加粗
                fontSize: fontChart(12), // ✅ 正确：数字的字体大小（比 name 大1px，抵消加粗的紧凑感）
              },
            },
            padding: [0, 0, 0, 4],
          },
          data: [
            {
              name: "Social Media",
              icon: "circle",
              textStyle: { color: "#454545" },
            },
            {
              name: "Direct booking",
              icon: "circle",
              textStyle: { color: "#454545" },
            },
            {
              name: "Information Platforms",
              icon: "circle",
              textStyle: { color: "#454545" },
            },
            { name: "OTAs", icon: "circle", textStyle: { color: "#454545" } },
          ],
        },
        series: [
          {
            name: "Access From",
            type: "pie",
            // borderWidth: 300, // 关键参数：控制间距大小
            // borderColor: 'rgba(255,255,255,0.8)', // 半透明间距
            borderColor: "#fff", // 关键参数：间距颜色
            radius: ["26%", "90%"],
            center: ["80%", "50%"],
            grid: {
              // 让图表距离容器上下左右都为 0，填满容器
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
            },
            avoidLabelOverlap: false,
            itemStyle: {
              borderWidth: 2,
              borderColor: "#fff",
            },
            label: {
              show: false,
              position: "inside",
              fontSize: fontChart(10),
              color: "#fff", // 设置 label 整体颜色为白色
              formatter: function (params) {
                const percent = params.percent;
                const name = params.name;
                // 对较长的名称进行换行处理，这里简单地以空格为分隔符进行换行
                const words = name.split(" ");
                let newName = "";
                const lineLength = 8; // 每行最多显示的字符数，可根据实际情况调整
                let line = "";
                for (let i = 0; i < words.length; i++) {
                  const word = words[i];
                  if (line.length + word.length + 1 <= lineLength) {
                    line += (line === "" ? "" : " ") + word;
                  } else {
                    newName += line + "\n";
                    line = word;
                  }
                }
                newName += line;
                return `{percentStyle|${percent}%}`; // 让百分比单独一行
              },
              align: "center", // 文字居中
              bleedMargin: 0,
              padding: [0, 0],
              rich: {
                percentStyle: {
                  padding: [1, 2],
                  width: 25,
                  height: 25,
                  align: "center",
                  verticalAlign: "middle",
                  fontSize: fontChart(10),
                  color: "#fff", // 确保百分比颜色为白色
                },
              },
            },
            emphasis: {
              scale: false,
              // 鼠标悬停时的样式设置和正常状态一致
              label: {
                show: true,
                position: "inside",
                color: "#fff",
                formatter: function (params) {
                  const percent = params.percent;
                  const name = params.name;
                  const words = name.split(" ");
                  let newName = "";
                  const lineLength = 8;
                  let line = "";
                  // for (let i = 0; i < words.length; i++) {
                  //   const word = words[i];
                  //   if (line.length + word.length + 1 <= lineLength) {
                  //     line += (line === "" ? "" : " ") + word;
                  //   } else {
                  //     newName += line + "\n";
                  //     line = word;
                  //   }
                  // }
                  newName += line;
                  return `${newName}\n{percentStyle|${percent}%}`;
                },
                align: "center",
                bleedMargin: 0,
                padding: [0, 0],
                rich: {
                  percentStyle: {
                    padding: [1, 2],
                    width: 25,
                    height: 25,
                    align: "center",
                    verticalAlign: "middle",
                    fontSize: 10,
                    color: "#fff",
                  },
                },
              },
              labelLine: {
                show: false,
              },
              itemStyle: {
                borderWidth: 2,
                borderColor: "#fff",
              },
            },
            labelLine: {
              show: false,
            },
            // data: [
            //   {
            //     value: 224,
            //     name: "Social Media",
            //     itemStyle: { color: "#A563EA" },
            //   },
            //   {
            //     value: 500,
            //     name: "Direct booking",
            //     itemStyle: { color: "#B2B2B2" },
            //   },
            //   {
            //     value: 364,
            //     name: "Information Platforms",
            //     itemStyle: { color: "#2FAA68" },
            //   },

            //   {
            //     value: 161,
            //     name: "OTAs",
            //     itemStyle: { color: "#4199E1" },
            //   },
            // ],
          },
        ],
      },
    };
  },
  computed: {
    // 计算属性：根据开关状态返回对应数据
    activeChartData() {
      return this.mediaSwitch
        ? this.chartData.allSources
        : this.chartData.socialMedia;
    },
  },
  methods: {
    handleSwitchChange(value) {
      // 强制异步更新避免可能的冲突
      // this.$emit("onSwitchChange", value);
      this.$store.commit("dashBoard/updateSwitchState", value);
      this.$nextTick(() => {
        this.mediaSwitch = value;
        this.updateChartData(value);
      });
    },
    updateChartData(isSocialMedia) {
      // 修正：更新正确的 series[0].data
      this.optionAnnular.series[0].data = isSocialMedia
        ? this.chartData.allSources
        : this.chartData.socialMedia;

      // 更新图例数据
      this.optionAnnular.legend.data = this.optionAnnular.series[0].data.map(
        (item) => ({
          name: item.name,
          icon: "circle",
          textStyle: { color: "#454545" },
        })
      );

      // 强制图表更新
      this.$nextTick(() => {
        if (this.$refs.pieChart && this.$refs.pieChart.refresh) {
          this.$refs.pieChart.refresh();
        }
      });
    },
    calculateChartSize() {
      if (!this.$refs.chartContainer) return;

      // 获取图表容器的实际可用宽度（已考虑父容器padding）
      const containerWidth = this.$refs.chartContainer.offsetWidth;

      // 直接使用容器宽度（减去必要的边距）
      this.chartWidth = `${containerWidth - 24}px`; // 24px为预留边距

      // 调试输出
      console.log("Calculated chart width:", this.chartWidth);
    },
  },
  mounted() {
    this.calculateChartSize(); // 初始化尺寸
    window.addEventListener("resize", this.calculateChartSize); // 监听窗口缩放
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.calculateChartSize); // 移除监听
  },
  watch: {
    activeChartData: {
      handler(newVal) {
        this.updateChartData(newVal);
      },
      deep: true, // 深度监听数据变化
    },
  },

  beforeDestroy() {
    // 销毁前释放图表资源
    if (this.chartInstance) {
      this.chartInstance.dispose();
      this.chartInstance = null;
    }
  },
  created() {
    this.updateChartData(this.mediaSwitch);
  },
};
</script>

<style lang="scss" scoped>
.social-media-chart-container {
  position: relative;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  height: 1.9583rem;
  border-radius: 0.0556rem;
  border: 1px solid #cdcccc;
  background: #fff;

  .social-media-info {
    // width: 1.875rem;
    // height: 1.7708rem;
    margin: 24px 45px 32px 24px;

    .platform-details {
      margin-bottom: 18px;

      .platform-title {
        font-size: 0.1389rem;
        font-weight: 600;
        margin-bottom: 16px;
        color: #454545;
      }

      .platform-review-count {
        font-size: .1667rem;
        font-weight: 700;
        color: #232323;
        margin-bottom: 3px;
      }

      .platform-review-label {
        font-size: .0694rem;
        font-weight: 400;
        color: #454545;
      }
    }

    .platform-switch {
      display: flex;
      justify-content: space-between;

      .switch-label {
        font-size: 0.0972rem;
        font-weight: 600;
        color: #6a6969;
        // margin-right: 124px;
        // width: 0.5833rem;
      }

      // 新增的样式，用于调整 el-switch 的文字位置
      // .el-switch {
      //   display: flex;
      //   align-items: center;
      //   justify-content: center;
      //   .el-switch__core {
      //     // 确保开关按钮内的文字也能正确居中
      //     display: flex;
      //     align-items: center;
      //     justify-content: center;
      //   }
      // }
    }
  }

  .chart-container {
    position: absolute;
    right: 0;
    top: 15px;
    margin: 37px 24px;
  }
}
</style>
